package com.zhugang.week04;

import java.util.ArrayList;
import java.util.List;

/**
 * @program algorithms
 * @description: reversePrint
 * @author: chanzhugang
 * @create: 2022/06/23 23:15
 */
public class ReversePrint4 {

    /**
     * 剑指offer 06. 从尾到头打印链表
     *
     * @param head
     * @return
     */
    List<Integer> list = new ArrayList<>();

    public int[] reversePrint(ListNode head) {
        // 递归
        reverse(head);
        // list 转数组
        int[] arr = new int[list.size()];
        int i = 0;
        for (Integer k : list) {
            arr[i++] = k;
        }
        return arr;
    }

    private void reverse(ListNode head) {
        if (head == null) {
            // 终止条件
            return;
        }
        reverse(head.next);
        list.add(head.val);
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

}